package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: DishController
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/8 21:01
 * @Version 1.0
 */

@Transactional
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId + ':' + #dishDto.status")
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
/*        //方法一:清理所有菜品的缓存
        Set keys = redisTemplate.keys("dish_*");//获取所有dish_开头的key
        redisTemplate.delete(keys);//删除这些key   */

        //方法二:清理当前分类下的缓存(新增的时候 推荐使用)
//        String key = "dish_" + dishDto.getCategoryId() + "_1";
//        redisTemplate.delete(key);

        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询菜品数据
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize, String name) {
        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);

        //records:List<Dish> 中没有分类名称, 根据菜品分类id来查询菜品分类数据,set进去
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            //获取菜品分类id,得到菜品对象,得到菜品分类名称
            String categoryName = categoryService.getById(dish.getCategoryId()).getName();
            //新建dishdto对象,将菜品名称set进去
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        Map data = new HashMap();
        data.put("records", dishDtos);
        data.put("total", (int) pageInfo.getTotal());
        return R.success(data);
        /*        IPage<Dish> pageInfo = new Page<>(page, pageSize);
        IPage<DishDto> dishDtoIPage = new Page<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);
        //排除records,拷贝属性
        BeanUtils.copyProperties(pageInfo, dishDtoIPage, "records");
        //records:List<Dish> 中没有分类名称, 根据菜品分类id来查询菜品分类数据,set进去
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            //获取菜品分类id,得到菜品对象,得到菜品名称
            String categoryName = categoryService.getById(dish.getCategoryId()).getName();
            //新建dishdto对象,将菜品名称set进去
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoIPage.setRecords(dishDtos);
        return R.success(dishDtoIPage);*/
    }

    /**
     * 根据id查询菜品信息和对应的口味信息(用于回显数据)
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品信息和对应的口味信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto) {
        //方法一:清理所有菜品的缓存(修改的时候推荐使用,修改可能会使得多张表发生变化)
//        Set keys = redisTemplate.keys("dish_*");//获取所有dish_开头的key
//        redisTemplate.delete(keys);//删除这些key

        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 修改售卖状态（起售，停售）
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> statusWithIds(@PathVariable Integer status, @RequestParam List<Long> ids) {
        //构造一个条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(ids != null, Dish::getId, ids);
        lqw.orderByDesc(Dish::getPrice);
        //根据条件进行批量查询
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            if (dish != null) {
                //把浏览器传入的status参数赋值给菜品
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("售卖状态修改成功");
    }

    /**
     * 批量删除菜品和单独删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional  //因为多表操作开启事务
    public R<String> delete(@RequestParam List<Long> ids) {
        //构造一个条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //判断浏览器传来的ids是否为空，并和菜品表中的id进行匹配
        lqw.in(ids != null, Dish::getId, ids);
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            //判断当前菜品是否在售卖阶段，0停售，1起售
            if (dish.getStatus() == 0) {
                //停售状态直接删除
                dishService.removeById(dish.getId());
                LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
                //根据菜品id匹配口味表中的菜品id
                dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
                //删除菜品id关联的口味表信息
                dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
            } else {
                return R.error("此菜品还在售卖阶段，删除影响销售！");
            }
        }
        return R.success("删除成功");
    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId + ':' + #dish.status")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        //动态key,方便保存每个分类下的菜品
        /*String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            //缓存有,直接返回
            return R.success(dishDtos);
        }*/
        //缓存没有直接查询数据库
        List<Dish> list = dishService.list(new LambdaQueryWrapper<Dish>()
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime));
        dishDtos = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //分类
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //口味
            List<DishFlavor> dishFlavorList = dishFlavorService.list(
                    new LambdaQueryWrapper<DishFlavor>()
                            .eq(DishFlavor::getDishId, item.getId()));
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        //redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
